package com.me.bbs.common;

import com.me.bbs.BbsApplication;
import com.me.bbs.entity.Administrator;
import com.me.bbs.entity.Ban;
import com.me.bbs.entity.Forum;
import com.me.bbs.exceptions.BanException;
import com.me.bbs.exceptions.NoAuthException;
import com.me.bbs.service.IAdministratorService;
import com.me.bbs.service.IBanService;
import com.me.bbs.service.IForumService;
import com.me.bbs.service.impl.AdministratorServiceImpl;
import com.me.bbs.service.impl.ForumServiceImpl;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Liming Wang
 * @Description
 * @Create 2023/1/30 17:26
 */

public class AuthUtils {
    private static IAdministratorService administratorService = BbsApplication.ac.getBean(IAdministratorService.class);
    private static IForumService forumService = BbsApplication.ac.getBean(IForumService.class);

    private static IBanService banService = BbsApplication.ac.getBean(IBanService.class);
    public static void checkAdmin(AdminType adminType, Long id) {
        Long uid = (Long) SessionUtils.getAttribute("user");
        Boolean adminExists = administratorService.lambdaQuery().eq(Administrator::getUser,uid)
                .eq(Administrator::getForum,id)
                .exists();
        Boolean ownerExists = forumService.lambdaQuery().eq(Forum::getOwner, uid)
                .eq(Forum::getId, id)
                .exists();

        if(adminType == AdminType.ADMIN && !( adminExists || ownerExists)) {
            throw new NoAuthException();
        }
        else if(adminType == AdminType.OWNER && ! ownerExists) {
            throw new NoAuthException();
        }
    }

    public static void checkBan(Long forumId) {
        Long uid = (Long) SessionUtils.getAttribute("user");
        Ban ban = banService.lambdaQuery().eq(Ban::getUser, uid).eq(Ban::getForum, forumId)
                .gt(Ban::getExpireAt, LocalDateTime.now()).one();
        if(ban != null)
            throw new BanException("您已被封禁至" + ban.getExpireAt() + "原因：" + ban.getReason());
    }
}
